package org.example.repeater;

import com.github.benmanes.caffeine.cache.Cache;
import jakarta.annotation.Resource;
import org.example.repeater.server.clientServer;
import org.example.repeater.server.deviceServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Set;

import static org.example.repeater.message.Constant.dataPref;

@SpringBootApplication
public class RepeaterApplication  implements InitializingBean, DisposableBean {
    private static final Logger log = LoggerFactory.getLogger(RepeaterApplication.class);
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    private Cache<String, Object> caffeineCache;
    @Value("${server.devicePort}")
    private int devicePort;
    public static void main(String[] args)  {

        SpringApplication.run(RepeaterApplication.class, args);
    }
    @Override
    public void afterPropertiesSet()  {
        redisTemplate.delete("127.0.0.1:7100");
        Set<String> set= redisTemplate.keys("*");
        for (String address : set) {
            new Thread(()->{
                try {
                    clientServer.start(address,caffeineCache);
                } catch (InterruptedException e) {
                    log.error("808网关连接失败{},原因如下:{}",address,e.getMessage());
                }
            }).start();
            List<String> range = redisTemplate.opsForList().range(address, 0, -1);
            caffeineCache.put(dataPref+address, range);
        }
        new Thread(()->{
            deviceServer.start(devicePort,caffeineCache);
        }).start();

    }

    @Override
    public void destroy() throws Exception {


    }



}
